package com.hrt.datasender.datasent.udp;

import com.btcode.common.MyLog;
import com.btcode.log.ILog;
import com.hrt.datasender.mq.MqKit;
import com.hrt.datasender.mq.model.MqModel;
import com.hrt.datasender.mq.model.PacketModel;
import com.hrt.datasender.web.operInfo.OperInfoService;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


/**
 * udp发送类
 * 张文成
 * 2019.09.18
 */
public class UdpSender {

	public static ILog log;

	private static UdpSender _instance;

	private static DatagramSocket udpSocket;

	public static UdpSender getInstance() {
        if (_instance == null) {
            _instance = new UdpSender();
        }
        return _instance;
    }

	public void start() throws Exception {
		log = MyLog.getInstance().getLogger(UdpSender.class.getName());
		customerDataMQ();
	}

	public static void sendUdpMsg(PacketModel mqModel) throws Exception{
		udpSocket = new DatagramSocket();
		String msg = mqModel.getMsg().toString();
		byte[] msgBytes = msg.getBytes();
		String ip = mqModel.getIp();
		int port = Integer.parseInt(mqModel.getPort());
		InetAddress address = InetAddress.getByName(ip);
		DatagramPacket udpPacket = new DatagramPacket(msgBytes, msgBytes.length, address, port);
		udpSocket.send(udpPacket);
		OperInfoService.getInstance().info("发送成功:"+msg,ip,port);
		udpSocket.close();
	}

	public static void customerDataMQ(){
        MqKit.consumeMsgFromBizDataMQ(new MqKit.MsgListener() {
            @Override
            public void onReceive(MqModel mqModel) {
                try {
                	PacketModel model = (PacketModel)mqModel;
                	log.info("准备发送UDP数据:" + model.getMsg());
					sendUdpMsg(model);
                } catch (Exception e) {
                    log.error("发送UDP业务消息包错误：", e);
                }
            }
        });
    }
}
